const CACHE_PREFIX = 'whatsapp_platform_';
const DEFAULT_EXPIRY = 5 * 60 * 1000; // 5分钟

/**
 * 设置缓存
 * @param {string} key 缓存键
 * @param {any} data 要缓存的数据
 * @param {number} expiry 过期时间(毫秒)
 */
export const setCache = (key, data, expiry = DEFAULT_EXPIRY) => {
  try {
    const cacheKey = `${CACHE_PREFIX}${key}`;
    const item = {
      value: data,
      expiry: Date.now() + expiry,
    };
    localStorage.setItem(cacheKey, JSON.stringify(item));
    return true;
  } catch (error) {
    console.error('缓存设置失败:', error);
    return false;
  }
};

/**
 * 获取缓存
 * @param {string} key 缓存键
 * @returns {any|null} 缓存数据或null
 */
export const getCache = (key) => {
  try {
    const cacheKey = `${CACHE_PREFIX}${key}`;
    const item = localStorage.getItem(cacheKey);
    
    if (!item) return null;
    
    const parsedItem = JSON.parse(item);
    
    // 检查是否过期
    if (parsedItem.expiry < Date.now()) {
      localStorage.removeItem(cacheKey);
      return null;
    }
    
    return parsedItem.value;
  } catch (error) {
    console.error('缓存获取失败:', error);
    return null;
  }
};

/**
 * 删除缓存
 * @param {string} key 缓存键
 */
export const removeCache = (key) => {
  try {
    const cacheKey = `${CACHE_PREFIX}${key}`;
    localStorage.removeItem(cacheKey);
    return true;
  } catch (error) {
    console.error('缓存删除失败:', error);
    return false;
  }
};

/**
 * 清理所有过期缓存
 */
export const cleanExpiredCache = () => {
  try {
    const now = Date.now();
    
    Object.keys(localStorage).forEach(key => {
      if (key.startsWith(CACHE_PREFIX)) {
        try {
          const item = JSON.parse(localStorage.getItem(key));
          if (item.expiry < now) {
            localStorage.removeItem(key);
          }
        } catch (e) {
          // 忽略解析错误
        }
      }
    });
  } catch (error) {
    console.error('清理过期缓存失败:', error);
  }
};

// 导出缓存服务
export default {
  setCache,
  getCache,
  removeCache,
  cleanExpiredCache
}; 